package org.funtester.performance.books.chapter10.section3;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.funtester.performance.books.chapter09.section3.UserBehavior;

import java.time.Duration;

public class UserBehaviorPool {

    public static void main(String[] args) throws Exception {
        GenericObjectPool<UserBehavior> userBehaviorPool = initUserBehaviorPool();// 初始化对象池
        UserBehavior userBehavior = userBehaviorPool.borrowObject();// 从对象池中获取对象
        userBehavior.id = 1;// 设置用户id
        userBehavior.action = "浏览商品";// 设置用户行为
        userBehavior.content = "商品ID:123456";// 设置用户行为内容
        userBehavior.timestamp = System.currentTimeMillis();// 设置用户行为时间戳
        System.out.println("第一次借出对象hashCode: " + userBehavior.hashCode());// 打印对象的hashcode
        System.out.println(userBehavior);// 打印对象内容
        userBehaviorPool.returnObject(userBehavior);// 归还对象
        UserBehavior userBehaviorSecond = userBehaviorPool.borrowObject();// 再次获取对象
        System.out.println("第二次借出对象hashCode: " + userBehaviorSecond.hashCode());// 打印对象的hashcode
        System.out.println(userBehaviorSecond);// 打印对象内容
        userBehaviorPool.close();// 关闭对象池
    }

    /**
     * 初始化UserBehavior对象池
     *
     * @return
     */
    public static GenericObjectPool<UserBehavior> initUserBehaviorPool() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(100);
        poolConfig.setMinIdle(10);
        poolConfig.setMaxIdle(20);
        poolConfig.setMaxWait(Duration.ofMillis(1000));
        poolConfig.setMinEvictableIdleTime(Duration.ofMillis(1000));
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(1000));
        return new GenericObjectPool<>(new UserBehaviorFactory(), poolConfig);
    }

}
